package com.it.day9;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * ClassName: ReentrantReadWriteLockDemo
 * Description: 演示读写锁
 *
 * @Author: csx
 * @Create: 2025/5/17 - 17:08
 * @version: v1.0
 */

class MyResource {
    Map<String, String> map = new HashMap<>();

    ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();

    public void write(String key, String value){
        rwLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "\t----正在写入");
            map.put(key,value);
            try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); }
            System.out.println(Thread.currentThread().getName() + "\t----写完成入");
        } finally {
            rwLock.writeLock().unlock();
        }
    }

    public void read(String key){
        rwLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "\t----正在读入");
            String result = map.get(key);
            System.out.println(Thread.currentThread().getName() + "\t----读入完成 " + result);
        } finally {
            rwLock.readLock().unlock();
        }
    }
}

public class ReentrantReadWriteLockDemo {
    public static void main(String[] args) {
        MyResource myResource = new MyResource();
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            new Thread(() -> {
                myResource.write(String.valueOf(finalI), String.valueOf(finalI));
            }, String.valueOf(i)).start();
        }

        for (int i = 0; i < 10; i++) {
            int finalI = i;
            new Thread(() -> {
                myResource.read(String.valueOf(finalI));
            }, String.valueOf(i)).start();
        }
    }
}























